const mongoose = require('mongoose');
const { Tag, Role, BackupSetting, Backup, NotificationSetting } = require('../src/models');
const config = require('../src/config/config');

// 连接数据库
mongoose.connect(config.mongoose.url, config.mongoose.options).then(() => {
  console.log('已连接到MongoDB');
  createTestData();
}).catch((error) => {
  console.error('连接MongoDB时出错:', error);
  process.exit(1);
});

async function createTestData() {
  try {
    // 清空现有数据
    await Promise.all([
      Tag.deleteMany({}),
      Role.deleteMany({}),
      BackupSetting.deleteMany({}),
      Backup.deleteMany({}),
      NotificationSetting.deleteMany({})
    ]);
    
    console.log('已清空现有测试数据');

    // 1. 创建标签测试数据
    const tagsData = [
      { name: '减脂', description: '适合减脂期间食用的食物', count: 45 },
      { name: '增肌', description: '适合增肌期间食用的高蛋白食物', count: 32 },
      { name: '低碳水', description: '低碳水化合物的食物', count: 28 },
      { name: '高蛋白', description: '富含蛋白质的食物', count: 56 },
      { name: '素食', description: '不含肉类的素食食物', count: 37 },
      { name: '低糖', description: '低糖分食物', count: 23 },
      { name: '低脂', description: '低脂肪食物', count: 31 },
      { name: '高纤维', description: '富含膳食纤维的食物', count: 19 }
    ];

    const tags = await Tag.insertMany(tagsData);
    console.log(`已插入${tags.length}个标签`);

    // 2. 创建角色测试数据
    const rolesData = [
      {
        name: '超级管理员',
        description: '拥有所有权限的最高级别管理员',
        permissions: [
          { module: 'user', actions: ['all'] },
          { module: 'food', actions: ['all'] },
          { module: 'recipe', actions: ['all'] },
          { module: 'diet', actions: ['all'] },
          { module: 'system', actions: ['all'] },
          { module: 'backup', actions: ['all'] },
          { module: 'statistics', actions: ['all'] }
        ]
      },
      {
        name: '内容管理员',
        description: '负责管理食物、食谱等内容的管理员',
        permissions: [
          { module: 'food', actions: ['view', 'create', 'update', 'delete'] },
          { module: 'recipe', actions: ['view', 'create', 'update', 'delete'] },
          { module: 'tag', actions: ['view', 'create', 'update', 'delete'] },
          { module: 'system', actions: ['view'] }
        ]
      },
      {
        name: '用户管理员',
        description: '负责管理用户账号和权限的管理员',
        permissions: [
          { module: 'user', actions: ['view', 'create', 'update', 'delete'] },
          { module: 'diet', actions: ['view'] },
          { module: 'system', actions: ['view'] }
        ]
      },
      {
        name: '数据分析员',
        description: '负责数据统计和分析的管理员',
        permissions: [
          { module: 'statistics', actions: ['view'] },
          { module: 'user', actions: ['view'] },
          { module: 'food', actions: ['view'] },
          { module: 'recipe', actions: ['view'] },
          { module: 'diet', actions: ['view'] }
        ]
      },
      {
        name: '系统维护员',
        description: '负责系统维护和备份的管理员',
        permissions: [
          { module: 'system', actions: ['view', 'update'] },
          { module: 'backup', actions: ['view', 'create', 'restore'] }
        ]
      }
    ];

    const roles = await Role.insertMany(rolesData);
    console.log(`已插入${roles.length}个角色`);

    // 3. 创建备份设置测试数据
    const backupSettingData = {
      autoBackup: true,
      frequency: 'weekly',
      retentionCount: 10,
      backupTime: '02:30',
      storageLocation: 'both'
    };

    const backupSetting = await BackupSetting.create(backupSettingData);
    console.log('已插入备份设置');

    // 4. 创建备份记录测试数据
    const today = new Date();
    const backupsData = [
      {
        date: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000), // 7天前
        type: 'auto',
        fileSize: 15640,
        status: 'success',
        filePath: '/backups/auto_backup_20231120.zip',
        errorMessage: ''
      },
      {
        date: new Date(today.getTime() - 14 * 24 * 60 * 60 * 1000), // 14天前
        type: 'auto',
        fileSize: 14980,
        status: 'success',
        filePath: '/backups/auto_backup_20231113.zip',
        errorMessage: ''
      },
      {
        date: new Date(today.getTime() - 21 * 24 * 60 * 60 * 1000), // 21天前
        type: 'auto',
        fileSize: 14520,
        status: 'success',
        filePath: '/backups/auto_backup_20231106.zip',
        errorMessage: ''
      },
      {
        date: new Date(today.getTime() - 3 * 24 * 60 * 60 * 1000), // 3天前
        type: 'manual',
        fileSize: 15720,
        status: 'success',
        filePath: '/backups/manual_backup_20231124.zip',
        errorMessage: ''
      },
      {
        date: new Date(today.getTime() - 1 * 24 * 60 * 60 * 1000), // 1天前
        type: 'manual',
        fileSize: 15980,
        status: 'failed',
        filePath: '/backups/manual_backup_20231126_failed.zip',
        errorMessage: '备份过程中断：存储空间不足'
      }
    ];

    const backups = await Backup.insertMany(backupsData);
    console.log(`已插入${backups.length}条备份记录`);

    // 5. 创建通知设置测试数据
    const notificationSettingData = {
      systemNotifications: {
        systemUpdate: true,
        securityAlert: true,
        backupResult: true
      },
      businessNotifications: {
        newUserRegistration: true,
        foodSubmission: true,
        recipePublication: false,
        userFeedback: true
      },
      notificationMethods: {
        inApp: true,
        email: true,
        sms: false,
        wechat: true
      },
      adminEmail: 'admin@healthyfood.com',
      priorityLevel: 'realtime'
    };

    const notificationSetting = await NotificationSetting.create(notificationSettingData);
    console.log('已插入通知设置');

    console.log('所有测试数据已成功创建！');
    
    // 关闭数据库连接
    mongoose.connection.close();
    console.log('已关闭MongoDB连接');
    process.exit(0);
  } catch (error) {
    console.error('创建测试数据时出错:', error);
    mongoose.connection.close();
    process.exit(1);
  }
} 